package com.news.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.news.entity.News;
import com.news.service.NewsService;

@SuppressWarnings("serial")
@WebServlet("/useraddnews")
public class UserAddNewsServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int flag = 0;
		HttpSession session=request.getSession();
		int user_id = (int) session.getAttribute("user_id");
		try {
			//1.创建工具类
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//2.创建上传工具类
			ServletFileUpload upload = new ServletFileUpload(factory);
			//限制单个文件上限为100kb
			upload.setFileSizeMax(1024*100);
			//3.解析请求，解析出表单列表项
			List<FileItem> items = upload.parseRequest(request);
			String title = "";
			String content = "";
			String news_type = "";
			String photo = "";
			String savePath = "";
			String filename = "";
			//遍历表单项，获取每一个表单项的值
			for (FileItem item : items) {
				String name = item.getFieldName();//获取表单项的name
				if (name.equals("title")) {
					title = item.getString("UTF-8");//获取用户名
				}else if(name.equals("content")){
					content = item.getString("UTF-8");
				}else if(name.equals("news_type")){
					news_type = item.getString("UTF-8");
				}else if(name.equals("photo")){
					//把文件上传到服务器中
					savePath = getServletContext().getRealPath("/upload");
					filename = item.getName();//获取文件名
					//给文件名添加uuid的前缀,避免文件重名现象
					filename = "图片序号：" + UUID.randomUUID() + "_" + filename;
					if(!filename.toLowerCase().endsWith(".jpg") && !filename.toLowerCase().endsWith(".png")){
						flag = 2;
						request.setAttribute("flag", flag);
						request.getRequestDispatcher("/news/useraddnews.jsp").forward(request, response);
						System.out.println("单个文件的后缀不对，必须是jpg或png");
						return;
					}
					File file = new File(savePath,filename);
					//判断upload文件夹是否存在，如果不存在则自动创建
					if(!file.getParentFile().exists()){
						file.getParentFile().mkdir();	
					}
					item.write(file);//将照片表单项的内容写入到服务器对应的文件中
				}	
			}
			System.out.println("标题："+title+"\n内容："+content+"\n类别："+news_type+"\n作者："+user_id+"\n文件名："+filename+"\n路径："+savePath);
			request.setAttribute("title", title);
			request.setAttribute("content", content);
			request.setAttribute("news_type", news_type);
			request.setAttribute("filename", filename);
			request.setAttribute("flag", flag);
			News news = new News();
			news.setTitle(title);
			news.setContent(content);
			news.setNews_type(news_type);
			news.setImage_url(filename);
			news.setUser_id(user_id);
			NewsService newsService = new NewsService();
			newsService.add(news);
			response.sendRedirect(request.getContextPath()+"/usernewslist");
		} catch (Exception e) {
			flag = 1;
			request.setAttribute("flag", flag);
			request.getRequestDispatcher("/news/useraddnews.jsp").forward(request, response);
			System.out.println("单个文件大小超出限制");
//			e.printStackTrace();
		}
	}
}
